import { createRouter, createWebHistory, createMemoryHistory } from 'vue-router'
import { getPlatformType } from '../utils/platform'

// 路由配置
const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: {
      title: '登录',
      showInTab: false,
      requiresAuth: false
    }
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    meta: {
      title: '首页',
      showInTab: true,
      icon: 'home',
      requiresAuth: true
    }
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('../views/About.vue'),
    meta: {
      title: '关于',
      showInTab: true,
      icon: 'info-circle',
      requiresAuth: true
    }
  },
  {
    path: '/settings',
    name: 'Settings',
    component: () => import('../views/Settings.vue'),
    meta: {
      title: '设置',
      showInTab: true,
      icon: 'cog',
      requiresAuth: true
    }
  },
  // PC端特有页面
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('../views/web/Dashboard.vue'),
    meta: {
      title: '数据看板',
      showInTab: false,
      requiresAuth: true,
      platform: ['web']
    }
  }
]

// 根据平台选择路由模式
const createHistory = () => {
  const platform = getPlatformType()
  // 小程序使用内存路由
  if (platform === 'mp-weixin') {
    return createMemoryHistory()
  }
  // 其他平台使用history模式
  return createWebHistory(import.meta.env.BASE_URL)
}

// 创建路由实例
const router = createRouter({
  history: createHistory(),
  routes: routes.filter(route => {
    // 根据平台过滤路由
    const platform = getPlatformType()

    // 如果路由没有指定平台限制，则所有平台都可见
    if (!route.meta || !route.meta.platform) return true
    // 只在指定平台显示
    return route.meta.platform.includes(platform)
  })
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title || '一码多端应用'
  
  // 微信小程序设置导航栏标题
  if (getPlatformType() === 'mp-weixin' && typeof wx !== 'undefined') {
    wx.setNavigationBarTitle({
      title: to.meta.title || '一码多端应用'
    })
  }
  
  // 权限验证
  if (to.meta.requiresAuth) {
    let token = localStorage.getItem('token')
    // 小程序使用其本地存储
    if (getPlatformType() === 'mp-weixin' && typeof wx !== 'undefined') {
      token = wx.getStorageSync('token')
    }
    
    if (!token) {
      // 未登录，跳转到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
      return
    }
  }
  
  next()
})

export default router
